<template>
  <div class="app-container">
    <el-row :gutter="10">
      <!--树结构-->
      <el-col :span="isHide ? 1 : 6" :xs="24" class="relative">
        <div class="app-container-tree-border">
          <project-tree-select-inner class="cd-mb8" :projectId="projectId" @changeProject="changeProject" />
          <el-input class="cd-mb8" v-model="filterText" placeholder="请输入" clearable size="small"
            prefix-icon="el-icon-search" />
          <el-tree class="input-tree" :data="treeList" :props="defaultProps" :filter-node-method="filterNode" ref="tree"
            node-key="id" highlight-current @node-click="handleNodeClick">
            <div slot-scope="{ node, data }" class="custom-tree-node" :title="node.label" v-text="node.label"></div>
          </el-tree>
          <div class="tree-hide-button iconfont" :class="isHide ? 'icon-xiangyou' : 'icon-xiangzuo'"
            @click="() => { isHide = !isHide }">
          </div>
        </div>
      </el-col>
      <el-col :span="isHide ? 23 : 18" :xs="24">
        <div class="app-container-table-border">
          <div class="header-title">
            <span>第</span>
            <el-select class="cd-ml8 cd-mr8" v-model="queryParams.measureQhId" placeholder="" size="mini"
              style="width: 60px" @change="qsChange">
              <el-option v-for="item in qsOptions" :key="item.measureQhId" :label="item.qh"
                :value="item.measureQhId"></el-option>
            </el-select>
            <span>期计量列表</span>
            <span v-if="qsInfo && qsInfo.beginDate" class="cd-ml8 cd-mr8"> ( {{ parseTime(qsInfo.beginDate,
              "{y}-{m}-{d}") }} - {{ parseTime(qsInfo.endDate, "{y}-{m}-{d}") }}) </span>
          </div>
          <el-row v-if="treeInfo && treeInfo.type == 'supplier'" :gutter="10"
            class="mb8 cd-pr8 top-right-btn small-line-height">
            <el-col :span="1.5" v-if="isReadonly">
              <el-button type="primary" plain size="mini" @click="onUpdate(false)"
                v-hasPermi="['ma:materialOtherMeasure:update']" :disabled="!canOperation()">编辑</el-button>
            </el-col>
            <el-col :span="1.5" v-else>
              <el-button type="primary" plain size="mini" @click="submitForm"
                v-hasPermi="['ma:materialOtherMeasure:update']" :disabled="!canOperation()">保存</el-button>
              <el-button type="primary" plain size="mini" @click="onUpdate(true)"
                v-hasPermi="['ma:materialOtherMeasure:update']" :disabled="!canOperation()">取消</el-button>
            </el-col>
          </el-row>
          <el-form ref="form" :model="form" :rules="rules" label-width="0px">
            <el-descriptions border title="" :column="3" size="medium" labelClassName="descriptions-label"
              contentClassName="descriptions-content">
              <el-descriptions-item label="索赔金额：" span="1">
                <span v-if="isReadonly">{{ form.spjr }}</span>
                <el-form-item v-else label="" prop="spjr">
                  <el-input v-model="form.spjr" placeholder="请输入索赔金额" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="违约罚金：" span="1">
                <span v-if="isReadonly">{{ form.wyfj }}</span>
                <el-form-item v-else label="" prop="wyfj">
                  <el-input v-model="form.wyfj" placeholder="请输入违约罚金" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="迟付款利息：" span="1">
                <span v-if="isReadonly">{{ form.cfklx }}</span>
                <el-form-item v-else label="" prop="cfklx">
                  <el-input v-model="form.cfklx" placeholder="请输入迟付款利息" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="扣留质保金：" span="1">
                <span v-if="isReadonly">{{ form.klzbj }}</span>
                <el-form-item v-else label="" prop="klzbj">
                  <el-input v-model="form.klzbj" placeholder="请输入扣留质保金" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="到期应退还质保金：" span="1">
                <span v-if="isReadonly">{{ form.dqythbzj }}</span>
                <el-form-item v-else label="" prop="dqythbzj">
                  <el-input v-model="form.dqythbzj" placeholder="请输入到期应退还质保金" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="其他：" span="1">
                <span v-if="isReadonly">{{ form.other }}</span>
                <el-form-item v-else label="" prop="other">
                  <el-input v-model="form.other" placeholder="请输入其他" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="备注：" span="3">
                <span v-if="isReadonly">{{ form.remark }}</span>
                <el-form-item v-else label="" prop="remark">
                  <el-input v-model="form.remark" placeholder="请输入备注" />
                </el-form-item>
              </el-descriptions-item>
              <el-descriptions-item label="附件：" span="3">
                <fileUpload v-model="form.fileId" :oldList="form.fileIdOld"
                  :fileType="['doc', 'docx', 'xlsx', 'xls', 'pdf', 'png', 'jpg', 'jpeg']" :disabled="isReadonly" />
              </el-descriptions-item>
            </el-descriptions>
          </el-form>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { allListMaterialMeasureQh } from "@/api/ma/materialMeasureQh";
import { listMaterialOtherMeasure, getMaterialOtherMeasure, delMaterialOtherMeasure, addMaterialOtherMeasure, updateMaterialOtherMeasure } from "@/api/ma/materialOtherMeasure";
import { querySupplierTreeList } from "@/api/base/bsBd";
import { getReportFormPaymentByQhId } from "@/api/ma/paymentReportForm";

import { mapGetters } from "vuex";

export default {
  name: "MaterialOtherMeasure",
  data () {
    return {
      isHide: false,
      treeList: [],
      treeInfo: {},
      defaultProps: {
        children: "children",
        label: "label"
      },
      filterText: undefined,
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      qsOptions: [],
      qsInfo: {},
      // 总条数
      total: 0,
      // 其他计量表格数据
      materialOtherMeasureList: [],
      isReadonly: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      workflowsStateus: "",
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        measureQhId: undefined,
        bdId: undefined,
        gysId: undefined,
        type: undefined,
        spjr: undefined,
        wyfj: undefined,
        cfklx: undefined,
        other: undefined,
        klzbj: undefined,
        dqythbzj: undefined,
        fileId: undefined
      },
      projectId: undefined,
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        // spjr: [
        //   { required: true, message: "索赔金额不能为空", trigger: "blur" }
        // ],
        // wyfj: [
        //   { required: true, message: "违约罚金不能为空", trigger: "blur" }
        // ],
        // cfklx: [
        //   { required: true, message: "迟付款利息不能为空", trigger: "blur" }
        // ],
        // other: [
        //   { required: true, message: "其他不能为空", trigger: "blur" }
        // ],
        // klzbj: [
        //   { required: true, message: "扣留质保金不能为空", trigger: "blur" }
        // ],
        // dqythbzj: [
        //   { required: true, message: "到期应退还质保金不能为空", trigger: "blur" }
        // ],
        // fileIds: [
        //   { required: true, message: "附件id不能为空", trigger: "blur" }
        // ],
      }
    };
  },
  computed: {
    ...mapGetters(["sysProjectId", "sysProjectList"])
  },
  watch: {
    sysProjectId (newVal, oldVal) {
      // 系统顶部选中项目变化
      this.changeProject(newVal);
    },
    filterText (val) {
      this.$refs.tree.filter(val);
    }
  },
  created () {
    this.changeProject();
  },
  methods: {
    changeProject (projectId = this.sysProjectId) {
      this.projectId = projectId;
      this.getBdTree();
    },
    getBdTree () {
      querySupplierTreeList({ projectId: this.projectId }).then((response) => {
        this.treeList = response.data;
        // 选中左侧树
        this.$nextTick(() => {
          if (this.treeList.length > 0) {
            // this.$refs.tree.setCurrentKey(this.treeList[0].id);
            // this.handleNodeClick(this.treeList[0]);
          } else {
            this.treeInfo = {};
            this.queryParams.bdId = null;
            this.queryParams.zdId = null;
            this.materialOtherMeasureList = [];
            this.total = 0;
            // this.handleQuery();
          }
        });
      });
    },
    // 筛选节点
    filterNode (value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick (data) {
      this.treeInfo = data;
      if (data.type == "supplier") {
        this.queryParams.zdId = data.parentId; // 站点ID
        this.queryParams.gysId = data.id; // 供应商ID
        this.getQsList();
      } else {
        // this.$message.warning("请选择供应商！");
      }
    },
    getQsList () {
      const query = {
        gysId: this.queryParams.gysId
      };
      allListMaterialMeasureQh(query).then((res) => {
        this.qsOptions = res.data;
        if (this.qsOptions.length > 0) {
          // 默认期数
          let qsInfo = this.qsOptions.find((item) => item.currentQhFlag == 1);
          if (!qsInfo) {
            qsInfo = this.qsOptions[this.qsOptions.length - 1];
          }
          this.qsInfo = qsInfo;
          this.queryParams.measureQhId = qsInfo.measureQhId;
          // this.queryParams.qs = qsInfo.qs;
          this.qsChange();
        } else {
          this.queryParams.measureQhId = null;
          this.workflowsStateus = "";
          this.total = 0;
          this.dataList = [];
          this.qsInfo = {};
        }
      });
    },
    qsChange () {
      this.qsInfo = this.qsOptions.find((item) => item.measureQhId == this.queryParams.measureQhId);
      this.getInfo();
      this.isReadonly = true;
      // 获取审批状态
      this.getWorkflowsStateus();
    },
    // 获取审批状态
    getWorkflowsStateus () {
      const query = {
        measureQhId: this.queryParams.measureQhId,
        gysId: this.qsInfo.gysId
      };
      getReportFormPaymentByQhId(query).then((response) => {
        const { workflowsStateus } = response.data;
        this.workflowsStateus = workflowsStateus || "00";
      });
    },
    getInfo () {
      getMaterialOtherMeasure(this.queryParams).then((response) => {
        if (response.data) {
          this.form = response.data;
        } else {
          this.reset();
        }
        if (this.form.fileId) {
          this.form.fileIdOld = this.form.fileId.split(",");
        }
      });
    },
    // 表单重置
    reset () {
      this.form = {
        otherMeasureId: undefined,
        measureQhId: this.queryParams.measureQhId,
        zdId: this.treeInfo.parentId,
        gysId: this.treeInfo.id,
        type: undefined,
        spjr: undefined,
        wyfj: undefined,
        cfklx: undefined,
        other: undefined,
        klzbj: undefined,
        dqythbzj: undefined,
        fileId: undefined,
        remark: undefined
      };
      this.resetForm("form");
    },
    // 是否可操作
    canOperation () {
      return this.workflowsStateus == "00" || this.workflowsStateus == "33";
    },
    onUpdate (isReadonly) {
      this.isReadonly = isReadonly;
      if (isReadonly) {
        this.getInfo();
      }
    },
    /** 提交按钮 */
    submitForm () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          this.buttonLoading = true;
          if (this.form.otherMeasureId != null) {
            updateMaterialOtherMeasure(this.form)
              .then((response) => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getInfo();
                this.isReadonly = true;
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          } else {
            addMaterialOtherMeasure(this.form)
              .then((response) => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getInfo();
                this.isReadonly = true;
              })
              .finally(() => {
                this.buttonLoading = false;
              });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      const otherMeasureIds = row.otherMeasureId || this.ids;
      this.$modal
        .confirm('是否确认删除其他计量编号为"' + otherMeasureIds + '"的数据项？')
        .then(() => {
          this.loading = true;
          return delMaterialOtherMeasure(otherMeasureIds);
        })
        .then(() => {
          this.loading = false;
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => { })
        .finally(() => {
          this.loading = false;
        });
    },
    /** 导出按钮操作 */
    handleExport () {
      this.download(
        "ma/materialOtherMeasure/export",
        {
          ...this.queryParams
        },
        `materialOtherMeasure_${new Date().getTime()}.xlsx`
      );
    }
  }
};
</script>
<style lang="scss" scoped>
.header-title {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 10px 0;
  font-size: 20px;
  font-weight: 700;
}

::v-deep {
  .descriptions-label {
    width: 140px;
    text-align: right !important;
    padding: 10px 0 !important;
  }

  .descriptions-content {
    // padding: 5px !important;

    .el-form-item {
      margin-bottom: 0px !important;
    }
  }
}
</style>
